package electricity.controller;

import electricity.Utils.AliOssUtil;
import electricity.domain.DirectoryNode;
import electricity.service.impl.DocumentService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
// 替换原来的 javax.servlet 导入
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

@RestController
@RequestMapping("/document")
@Tag(name = "文档管理接口")
public class DocumentController {

    private final DocumentService documentService;
    private final AliOssUtil ossUtil; // 注入 OSS 工具类，用于下载文件

    // 构造方法注入（新增 ossUtil）
    public DocumentController(DocumentService documentService, AliOssUtil ossUtil) {
        this.documentService = documentService;
        this.ossUtil = ossUtil;
    }

    /**
     * 获取目录树（前端调用 /api/document/directories）
     */
    @GetMapping("/directories")
    @Operation(summary = "获取目录树")
    public List<DirectoryNode> getDirectoryTree() {
        return documentService.getDirectoryTree();
    }

    /**
     * 获取指定目录下的文件列表（前端调用 /api/document/files）
     */
    @GetMapping("/files")
    @Operation(summary = "获取指定目录下的文件列表")
    public List<AliOssUtil.OssFile> getFiles(
            @RequestParam String directory,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "50") Integer limit) {
        List<AliOssUtil.OssFile> allFiles = documentService.getFilesInDirectory(directory);
        int start = (page - 1) * limit;
        int end = Math.min(start + limit, allFiles.size());
        return allFiles.subList(start, end);
    }

    /**
     * 上传文件到指定目录（前端调用 /api/document/upload）
     */
    @PostMapping("/upload")
    @Operation(summary = "上传文件到指定目录")
    public ResponseEntity<String> uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam String directory) throws IOException {
        String fileUrl = documentService.uploadFileToDirectory(file, directory);
        return ResponseEntity.ok("文件上传成功：" + fileUrl);
    }

    /**
     * 新增：文件下载接口（前端调用 /api/document/download）
     */
    @GetMapping("/download")
    @Operation(summary = "下载文件到本地")
    public void downloadFile(
            @RequestParam String path,
            HttpServletResponse response) throws IOException {
        // 从 OSS 获取文件输入流
        try (InputStream inputStream = ossUtil.download(path)) {
            // 设置响应头（指定文件名和下载方式）
            String fileName = path.substring(path.lastIndexOf("/") + 1);
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION,
                    "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
            response.setContentType("application/octet-stream");

            // 将文件流写入响应
            try (OutputStream outputStream = response.getOutputStream()) {
                byte[] buffer = new byte[4096];
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
            }
        }
    }

    /**
     * 新增：文件删除接口（可选）
     */
    @DeleteMapping("/delete")
    @Operation(summary = "删除指定文件")
    public ResponseEntity<String> deleteFile(@RequestParam String path) {
        ossUtil.deleteFile(path); // 需要在 AliOssUtil 中实现 deleteFile 方法
        return ResponseEntity.ok("文件删除成功");
    }
}
